<?php

namespace App\Jobs;

use App\Http\Service\DeviceService;
use App\Model\Device;
use App\Model\DeviceBus;
use App\Model\DeviceBuslog;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;


class AutoPower implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $deviceBusId;
    public $tries = 1;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($deviceBusId)
    {
        $this->deviceBusId = $deviceBusId;
        //因为要导入大文件 需要很久时间
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $busInfo = DeviceBus::query()->find($this->deviceBusId);
        if (!$busInfo) {
            Log::info('无公摊信息-----' . $this->deviceBusId);
            return '';
        }
        $mainDevice = Device::query()->where('id', $busInfo->device_id)
            ->first();
        if (!$mainDevice) {
            Log::info('无主摊表信息-----' . $busInfo->device_id);
            return '';
        }
        $log = DeviceBuslog::query()->where('main_device_id', $mainDevice->id)
            ->orderBy('id', 'desc')
            ->where('type',1)
            ->first();
        if($log){
            $before = $log->created_at;
            $du = $mainDevice->total-$log->main_du;
        }else{
            $before = $busInfo->created_at;
            $du = $mainDevice->total-$busInfo->device_total;
        }
        $memCount = DeviceBus::query()->where('pid',$busInfo->id)
            ->where('status',1)->count();
        if($memCount <= 0){
            $busInfo->device_total = $mainDevice->total;
            $busInfo->save();
        }
        Log::info($this->deviceBusId.'模式'.$busInfo->count_type.'---主摊表度数差-----'. $du);
        if($du > 100){
            return ;
        }
        if ($du > 0 && $memCount > 0) {
            if($busInfo->count_type == 2){
                $memInfo = DeviceBus::query()->where('pid',$busInfo->id)
                    ->get();
                $diff = 0;
                $tempMem = [];
                foreach($memInfo as $v){
                    $device = Device::query()->find($v->device_id);
                    $tempMem[$v->device_id]['now'] = $device->total;
                    $tempMem[$v->device_id]['old'] = $v->device_total;
                    $diff += ($device->total-$v->device_total);
                    $v->device_total = $device->total;
                    $v->save();
                }
                Log::info( $this->deviceBusId.'总表新增度---'.$du.'总表模式-子表度数和-----' . $diff.'明细：'.json_encode($tempMem));
                if($du > $diff){
                    $busDu = $du - $diff;
                    $mainLog = new DeviceBuslog();
                    $mainLog->main_device_id = $busInfo->device_id;
                    $mainLog->main_du = $mainDevice->total;
                    $mainLog->mac = $mainDevice->mac;
                    $mainLog->business_id = $mainDevice->business_id;
                    $mainLog->type = 1;
                    $mainLog->du = $busDu;
                    $mainLog->status = 1;
                    $mainLog->class_id = $busInfo->class_id;
                    $mainLog->before_time = $before;
                    $mainLog->count_type = 2;
                    $mainLog->save();
                    $service = app()->make(DeviceService::class);
                    $memInfo = DeviceBus::query()->where('pid',$busInfo->id)
                        ->where('status',1)
                        ->get();
                    foreach($memInfo as $k => $mem){
                        try{
                            $du1 = number_format(($busDu*$mem->rate)/100,2,'.','');
                            if($du1 > 0){
                                $slog = new DeviceBuslog();
                                $slog->log_id = $mainLog->id;
                                $slog->main_device_id = $busInfo->device_id;
                                $slog->mem_device_id = $mem->device_id;
                                $slog->main_du = $mainDevice->total;
                                $slog->du = $du1;
                                $slog->rate = $mem->rate;
                                $memDevice = Device::query()->where('id',$mem->device_id)
                                    ->first();
                                $slog->mac =$memDevice->mac;
                                $slog->mem_du = $memDevice->du;
                                $slog->type = 2;
                                $slog->class_id = $busInfo->class_id;
                                $slog->count_type = 2;
                                $slog->save();
                                $service->editDu($memDevice->mac,$slog->du);
                                dispatch(new CheckReduce($slog->id))->delay(120);
                            }
                        }catch (\Exception $e){
                            Log::info($e->getMessage());
                        }
                    }
                }
                $busInfo->device_total =  $mainDevice->total;
                $busInfo->save();
            }else{
                $memInfo = DeviceBus::query()->where('pid',$busInfo->id)
                    ->where('status',1)
                    ->get();
                $mainLog = new DeviceBuslog();
                $mainLog->main_device_id = $busInfo->device_id;
                $mainLog->main_du = $mainDevice->total;
                $mainLog->mac = $mainDevice->mac;
                $mainLog->business_id = $mainDevice->business_id;
                $mainLog->type = 1;
                $mainLog->du = $du;
                $mainLog->status = 1;
                $mainLog->class_id = $busInfo->class_id;
                $mainLog->before_time = $before;
                $mainLog->save();
                $service = app()->make(DeviceService::class);
                foreach($memInfo as $k => $mem){
                    try{
                        $du1 = number_format(($du*$mem->rate)/100,2,'.','');
                        if($du1 > 0){
                            $slog = new DeviceBuslog();
                            $slog->log_id = $mainLog->id;
                            $slog->main_device_id = $busInfo->device_id;
                            $slog->mem_device_id = $mem->device_id;
                            $slog->main_du = $mainDevice->total;
                            $slog->du = $du1;
                            $slog->rate = $mem->rate;
                            $memDevice = Device::query()->where('id',$mem->device_id)
                                ->first();
                            $slog->mac =$memDevice->mac;
                            $slog->mem_du = $memDevice->du;
                            $slog->type = 2;
                            $slog->class_id = $busInfo->class_id;
                            $slog->save();
                            $service->editDu($memDevice->mac,$slog->du);
                            dispatch(new CheckReduce($slog->id))->delay(120);
                        }
                    }catch (\Exception $e){
                        Log::info($e->getMessage());
                    }
                }
            }
        }
    }
}

